<?php 
    date_default_timezone_set("Asia/Saigon");   
    function getVideoInfo($id)
    {
        $sql = "SELECT id, title,title_sms FROM c_video WHERE id=" . $id;
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;
    }
    
    function getUserInfo($id)
    {
        $sql = "SELECT id,refCode,username FROM c_user WHERE id=" . intval($id);
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;    
    }
    
    function getGameInfo($id)
    {
        $sql = "SELECT id,title,partnerId,percent_wapmaster,percent_partner FROM c_game WHERE id=" .intval($id);
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;    
    }
    
     function getAppInfo($appHeader)
    {
        $sql = "SELECT id,title,partnerId,percent_wapmaster,percent_partner FROM c_app WHERE id = '".intval($appHeader)."' OR appHeader='" . $appHeader."'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;    
    }
    
    
    function getSMSLogByTransactionId($MOId)
    {
        $sql = "SELECT id,userId,transactionId,responseId,status,mo FROM c_sms_log WHERE transactionId=" . $MOId;
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;    
    }
    
    function getCardLogToCharg()
    {
        $sql = "SELECT * FROM c_card_log WHERE status=0 limit 10" ;
        $result = @mysql_query($sql);    
        $rows = array();
        
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        } 
        
      //  var_dump($rows) ;die;
        return $rows;    
    }
    
     function getSMSLogNotSendMT()
    {
        $sql = "SELECT * FROM c_sms_log WHERE status_send_mt= 0" ;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
  //      mysql_free_result($result);
        return $rows;    
    }
    
    
    function getAlbumInfo($id)
    {
        $sql = "SELECT id,title,title_sms FROM c_album WHERE id=" . $id;
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;    
    }
    
    function getTotalImageInAlbum($id)
    {
        $sql = "SELECT count(id) FROM c_image WHERE albumId=" . $id;
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows["count(id)"];    
    }
    
     function checkTransactionExist($transactionId)
    {
        $sql = "SELECT count(transactionId) FROM c_sms_log WHERE transactionId='" . $transactionId."'";
       
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows["count(transactionId)"];    
    }
    
    
    function InsertDataDownload($data)
    {
        $sql = "INSERT INTO c_data_download SET 
            `dataId`=" . mysql_escape_string($data["id"]) . "
            , `type`=" . mysql_escape_string($data["type"]) . "                        
            , `transactionId`=" . mysql_escape_string($data["transactionId"]) . "                        
        ";        
        $result = @mysql_query($sql);
        $dataDownloadId = mysql_insert_id();
        return $dataDownloadId;   
    }
    
    
    function InsertSmsLog($data)
    {
        $sql = "INSERT INTO c_sms_log SET 
            `userId`='" . mysql_escape_string($data["userId"]) . "'
            , `partnerId`=" . mysql_escape_string($data["partnerId"]) . "
            , `type`=" . mysql_escape_string($data["type"]) . "
            , `os_type`=" . mysql_escape_string($data["os_type"]) . "
            , `dataId`=" . mysql_escape_string($data["dataId"]) . "
            , `appId`=" . mysql_escape_string($data["appId"]) . "
            , `mo`='" . mysql_escape_string($data["mo"]) . "'
            , `mt`='" . mysql_escape_string($data["mt"]) . "'
            , `mobile`='" . mysql_escape_string($data["mobile"]) . "'
            , `telco`='" . mysql_escape_string($data["telco"]) . "'
            , `serviceNumber`=" . mysql_escape_string($data["serviceNumber"]) . "
            , `price`=" . mysql_escape_string($data["price"]) . "
            , `status`=" . mysql_escape_string($data["status"]) . "
            , `transactionId`=" . mysql_escape_string($data["transactionId"]) . "
            , `day`=" . date("d") . "
            , `month`=" . date("m") . "
            , `year`=" . date("Y") . "
            , `percent_wapmaster`=" . $data["percent_wapmaster"] . "
            , `percent_partner`=" . $data["percent_partner"] . "
            , `status_mo`=" . $data["status_mo"] . "
            , `status_send_mt`=" . $data["status_send_mt"] . "
            , `create_date`=" . time() . "
        ";        
        
        //echo $sql;
        $result = @mysql_query($sql);
        return $result;    
    }
    
    
    function UpdateSmsLog($data)
    {
        $sql = "UPDATE  c_sms_log SET 
            `userId`='" . mysql_escape_string($data["userId"]) . "'
            , `partnerId`=" . mysql_escape_string($data["partnerId"]) . "
            , `type`=" . mysql_escape_string($data["type"]) . "
            , `dataId`=" . mysql_escape_string($data["dataId"]) . "
            , `mo`='" . mysql_escape_string($data["mo"]) . "'
            , `mt`='" . mysql_escape_string($data["mt"]) . "'
            , `mobile`='" . mysql_escape_string($data["mobile"]) . "'
            , `telco`='" . mysql_escape_string($data["telco"]) . "'
            , `serviceNumber`=" . mysql_escape_string($data["serviceNumber"]) . "
            , `price`=" . mysql_escape_string($data["price"]) . "
            , `status`=" . mysql_escape_string($data["status"]) . "
            , `percent_wapmaster`=" . $data["percent_wapmaster"] . "
            , `percent_partner`=" . $data["percent_partner"] . "
            , `status_mo`=" . $data["status_mo"] . "
            , `status_send_mt`=" . $data["status_send_mt"] . "
            , `update_date`=" . time() .  " Where transactionId = '".$data["transactionId"]."'";        
        
      //  echo $sql;
        $result = @mysql_query($sql);
        return $result;    
    }
    
    
      function UpdateCardLog($data)
    {
        $sql = "UPDATE  c_card_log SET 
            `request`='" . mysql_escape_string($data["request"]) . "'
            , `charg_status`=" . mysql_escape_string($data["charg_status"]) . "
            , `status`=" . mysql_escape_string($data["status"]) . "
            , `requested_date`=" . mysql_escape_string($data["requested_date"]) . "
            , `response`='" . mysql_escape_string($data["response"]) . "'
            , `response_status`='" . mysql_escape_string($data["response_status"]) . "'
            , `responsed_date`='" . mysql_escape_string($data["responsed_date"]) . "'
            , `transactionId`='" . mysql_escape_string($data["transactionId"]) . "'".
             " Where id = '".$data["id"]."'";        
        
      //  echo $sql;
        $result = @mysql_query($sql);
        return $result;    
    }
    
    function UpdateTimeDownload($id,$type){
        switch($type){
            case 1:
                $table = "c_game";
                break; 
            case 2:
                $table = "c_video";
                break;
            case 3:
                $table = "c_album";
                break;
            default:
                $table = "";
                break;
        }
        if($table !=""){
            $sql = "UPDATE ".$table." SET time_download = ".time()." WHERE id =".intval($id);
            $result = @mysql_query($sql);
            return $result;
        }else{
            return 0;
        }
    }
    
    function InsertDataDownloadImage($data)
    {
        $sql = "SELECT id FROM c_image WHERE albumId=" . $data["id"];
        $result = @mysql_query($sql);            
        while($row = @mysql_fetch_assoc($result)){
            $sql = "INSERT INTO c_data_download_image SET 
                `imageId`=" . mysql_escape_string($row["id"]) . "            
                , `transactionId`=" . mysql_escape_string($data["transactionId"]) . "                        
            ";        
            @mysql_query($sql);
        }
        
        return $result;
    }
    
    function UpdateSMSLogByMe($id,$mt,$status,$status_send_mt,$responseId){
            $mt = mysql_escape_string($mt) ;
            $sql = "UPDATE c_sms_log SET mt = '".$mt."', status = $status ,responseId = '".$responseId."', status_send_mt = $status_send_mt WHERE id =".intval($id);
            $result = @mysql_query($sql);
            return $result;
    }
    
    function UpdateUserPass($id,$pass)
    {
            $pass=genPass($pass);
            $sql = "UPDATE c_user SET password = '".$pass."' WHERE id =".intval($id);
            $result = @mysql_query($sql);
            return $result;
    }
    
   
    function getUserByRefCode($refCode)
    {
        $sql = "SELECT id FROM c_user WHERE refCode='" . mysql_escape_string($refCode) . "'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;   
    }
    function getUserByUsername($username)
    {
        $sql = "SELECT id, active FROM c_user WHERE `username`='" . mysql_escape_string($username) . "'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;   
    }
    
     function getCUserByMobile($mobile)
    {
        $sql = "SELECT id, active FROM c_user WHERE `mobile`='" . mysql_escape_string($mobile) . "'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;   
    }
    
    function listServiceCode()
    {
        return array("8077","8177","8577", "8677", "8777");
    }
    
    function listTypeApp(){
        return array(1=>"j2me",2=>"android",3=>"ios");
    }
    
    function removeSign($str) {
        $coDau = array ("à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ", "ặ", "ẳ", "ẵ", "è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ", "ì", "í", "ị", "ỉ", "ĩ", "ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ", "ờ", "ớ", "ợ", "ở", "ỡ", "ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ", "ỳ", "ý", "ỵ", "ỷ", "ỹ", "đ", "À", "Á", "Ạ", "Ả", "Ã", "Â", "Ầ", "Ấ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ằ", "Ắ", "Ặ", "Ẳ", "Ẵ", "È", "É", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ề", "Ế", "Ệ", "Ể", "Ễ", "Ì", "Í", "Ị", "Ỉ", "Ĩ", "Ò", "Ó", "Ọ", "Ỏ", "Õ", "Ô", "Ồ", "Ố", "Ộ", "Ổ", "Ỗ", "Ơ", "Ờ", "Ớ", "Ợ", "Ở", "Ỡ", "Ù", "Ú", "Ụ", "Ủ", "Ũ", "Ư", "Ừ", "Ứ", "Ự", "Ử", "Ữ", "Ỳ", "Ý", "Ỵ", "Ỷ", "Ỹ", "Đ", "ê", "ù", "à" );

        $khongDau = array ("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "y", "y", "y", "y", "y", "d", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "E", "I", "I", "I", "I", "I", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "U", "Y", "Y", "Y", "Y", "Y", "D", "e", "u", "a" );
        $str = str_replace ($coDau, $khongDau, $str);
        $str = trim($str);
        return $str;
    }
    
    function cleanQuery($string)
    {        
        if(empty($string)) return $string;
        $string = mysql_escape_string(trim($string));
        
        $badWords = array(
            "/Select(.*)From/i"
            , "/Union(.*)Select/i"
            , "/Update(.*)Set/i"
            , "/Delete(.*)From/i"
            , "/Drop(.*)Table/i"
            , "/Insert(.*)Into/i"                
            , "/http/i"
            , "/--/i"
        );
        
        $string = preg_replace($badWords, "", $string);

        return $string;
    }
        
    function linkDownloadGame($gameId, $dataDownloadId)
    {
        return baseUrl() . "tai-ngay-game-" . encodeHex($gameId) . "-" . encodeHex($dataDownloadId);
    }
    
    function linkDownloadVideo($videoId, $dataDownloadId)
    {
        return trim(baseUrl(). "tai-ngay-video-" . encodeHex($videoId) . "-" . encodeHex($dataDownloadId));
    }    
    
    function linkDownloadImage($albumId, $dataDownloadId)
    {
        return baseUrl() . "tai-ngay-bo-anh-hot-" . encodeHex($albumId) . "-" . encodeHex($dataDownloadId);    
    }
    
    function genRefCode($id){
        return md5(md5($id) . "CunKIEmTieN$#$@$%");
    }
    
    function encodeHex($id)
    {    
        $str = dechex($id + 27111986);        
        $subStr = substr(dechex($id + 26101984), -5); //last three characters        
        $str = $str . $subStr;
        
        return $str;
    }
    
    function titleLen()
    {
        return 160;
    } 
    function checkTelco($mobile)
    {        
        $first = substr($mobile, 0, 1);
        if($first=="0"){
            $mobile = substr($mobile, 1, strlen($mobile) - 1);
        } else if($first="8"){
            $mobile = substr($mobile, 2, strlen($mobile) - 2);
        }
        
        $mobile = "84" . $mobile;
        
        $patternViettel = "/^84(9[678]|16[2-9])[\d]{7}/";
        $patternMobi = "/^84(9[03]|12[01268])[\d]{7}/";
        $patternVina = "/^84(9[14]|12[34579])[\d]{7}/";
        $patternVnmobile = "/^84(9[2]|18[86])[\d]{7}/";
        $patternBeeline = "/^84(9[9]|19[9])[\d]{7}/";
        
        if(preg_match($patternViettel, $mobile)){
            $telco = "1";    
        } else if(preg_match($patternMobi, $mobile)){
            $telco = "2";
        } else if(preg_match($patternVina, $mobile)){
            $telco = "3";
        } else if(preg_match($patternVnmobile, $mobile)){
            $telco = "4";
        } else if(preg_match($patternBeeline, $mobile)){
            $telco = "5";
        } else {
            $telco = "0";
        }
        
        return $telco;    
    }     
    function priceServiceCode($serviceCode)
    {
        $pattern_0 = "/^(\d)0(\d)(\d)$/si";
        $pattern_1 = "/^(\d)1(\d)(\d)$/si";
        $pattern_2 = "/^(\d)2(\d)(\d)$/si";
        $pattern_3 = "/^(\d)3(\d)(\d)$/si";
        $pattern_4 = "/^(\d)4(\d)(\d)$/si";
        $pattern_5 = "/^(\d)5(\d)(\d)$/si";
        $pattern_6 = "/^(\d)6(\d)(\d)$/si";        
        $pattern_7 = "/^(\d)7(\d)(\d)$/si";        
        
        $price = 0;
        if(preg_match($pattern_0, $serviceCode)){
            $price = 500;    
        } else if(preg_match($pattern_1, $serviceCode)){
            $price = 1000;    
        } else if(preg_match($pattern_2, $serviceCode)){
            $price = 2000;    
        } else if(preg_match($pattern_3, $serviceCode)){
            $price = 3000;    
        } else if(preg_match($pattern_4, $serviceCode)){
            $price = 4000;    
        } else if(preg_match($pattern_5, $serviceCode)){
            $price = 5000;    
        } else if(preg_match($pattern_6, $serviceCode)){
            $price = 10000;    
        } else if(preg_match($pattern_7, $serviceCode)){
            $price = 15000;    
        } 
        return $price;
    }
    
    
    function getUserByMobile($mobile){
        $sql = "SELECT * FROM user_clip WHERE mobile = '".$mobile."' ";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);        
        return $rows;
    }
    
      function insertUser($data){
        $mobile = mysql_escape_string($data["mobile"]);
        $status = intval($data["status"]);
        $end_date = intval($data["end_date"]);
        $create_date = mysql_escape_string($data["create_date"]);
        $create_user = mysql_escape_string($data["mobile"]);
        $sql = "INSERT INTO user_clip(mobile,status,end_date,create_date,create_user) 
        VALUES ('".$mobile."',".$status.",".$end_date.",".$create_date.",'".$create_user."')";
        $result = @mysql_query($sql);
        return $result;
    }
    
    function updateUser($data){
        $mobile = mysql_escape_string($data["mobile"]);
        $end_date = intval($data["end_date"]);
        $sql = "UPDATE user_clip SET end_date = ".$end_date." WHERE mobile = '".$mobile."'";
        $result = @mysql_query($sql);
        return $result;
    }
    
      function checkMobile($mobile)
    {        
        $first = substr($mobile, 0, 1);
        if($first=="0"){
            $mobile = substr($mobile, 1, strlen($mobile) - 1);
        } else if($first="8"){
                $mobile = substr($mobile, 2, strlen($mobile) - 2);
            }

            $mobile = "84" . $mobile;

        return $mobile;    
    }
    
     function displayMobile($mobile){
        $first = substr($mobile, 0, 2);
        if($first=="84"){
            $mobile = substr($mobile, 2, strlen($mobile) - 2);
            $mobile = "0" . $mobile;
        } 
        return $mobile;
    }
    
    function genLinkClip($mobile){
        $link = "http://clipvl.net/login?m=".$mobile;
        return $link;
    }
    
    function getGameIdByCMDCodeMeCord($cmdCode){
        $dataCmds = array("MTPME4"=>1,"MTPME5"=>2,"MTPME7"=>3,"MTPME2"=>4,"MTPME3"=>5,"MTPDTD"=>6,"MTPME1"=>7,"MTPME8"=>8,"MTPVTL"=>11,"MTPME9"=>10,"MTPKH1"=>12,"MTPKH2"=>13,"MTPKH3"=>14,"MTPKH4"=>15,"MTPKH5"=>16,"MTPKH6"=>17,"MTPTNO"=>18);
       
        $gameId = 0;
        foreach($dataCmds as $key => $value){
            if(strcasecmp($key,$cmdCode)==0) {
                $gameId = $value;
                break;
            }
        }
        return $gameId;
    }
    
    
    function sendMOMeCorp($requestId,$telco,$serviceNumber,$phone,$syntax,$mesage){
        $data = array();
        $name = "vintelcom";
        $accountName = "vintelcom";
        $dateIime =date('Y-m-d H:i:s');
        $privateKey= "wIOsFEeLoNc6mOf";
                                                         
        $data["Name"] =$name;
        $data["AccountName"] = $accountName;            
        $data["MOId"] = $requestId; 
        $data["Telco"] = $telco;
        $data["ServiceNum"] =$serviceNumber; 
        $data["Phone"] =$phone;                      
        $data["Syntax"] =$syntax;                      
        $data["Message"] =$mesage;                      
        $data["DateTime"] =$dateIime;
        
        $chuoiToken =  $name.$accountName. $data["MOId"].$data["Telco"].$data["ServiceNum"].$data["Phone"].$data["Syntax"] .$data["Message"] .$data["DateTime"] .$privateKey;
       $token = MD5($chuoiToken) ;
       $data["Token"] =$token;                                           
       //http://123.30.140.173:7777/sms/mo?WSDL             
       $client = new SoapClient("http://sms.gateway.gomobi.vn:7777/sms/mo?WSDL");
       //$client = new SoapClient("http://123.30.140.173:7777/sms/mo?WSDL");
       $result =  $client->__call("SendMO", $data);        

       return $result;
  }
  
  //sendMToGateWay( $ServiceNum,$Phone,$cmdCode,$Content,$MOId,$operator, $Charging,  0);
    function sendMToGateWay($serviceId,$userId,$providerId,$info,$requestId,$operator,$msgType,$contentType){
        
       //  header('Content-Type: text/plain; charset=UTF-8');
         $soapClient =  new SoapClient('http://service.10h.vn:8080/services/ReceiverMT?wsdl',array(
                // Stuff for development.
                'trace' => 1,
                'encoding'=>'utf-8',
                'exceptions' => true,
                'cache_wsdl' => WSDL_CACHE_NONE,
                'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
                // Auth credentials for the SOAP request.
                'login' => 'wsvintelcom',
                'password' => 'wsvintelcom!@#',
                // Proxy url.
                'proxy_host' => 'service.10h.vn', // Do not add the schema here (http or https). It won't work.
                'proxy_port' => 8080,
                // Auth credentials for the proxy.
                'proxy_login' => NULL,
                'proxy_password' => NULL,
            )
        ); 
       
         $data2 = array();
         $data2["serviceId"] =$serviceId ; //Đầu số dịch vụ.
         $data2["userId"] =$userId ; //Số điện thoai người dùng.
         $data2["providerId"] =$providerId; //Mã dịch vụ.
         $data2["info"] =base64_encode($info); // Nội dung MT
         $data2["requestId"] =$requestId; //MoID (requestId)
         $data2["operator"] =$operator; //telco
         $data2["msgType"] =$msgType; //1 = Tính cước. 0 = Không tính cước.
         $data2["contentType"] =$contentType;  //  0 = Text. 
             
         $result =  $soapClient->__soapCall("mtReceiver", $data2);     
         
         return $result;
    }
    
    
  
   // Get MT From ViVoo 
    function getMTFromViVoo($moid,$src,$dest,$cmdcode,$msgbody){
         $mo = str_replace(" ", "+", $msgbody);
         $username = "tritueviet_8x55";
         $password ="Xz649Bvw";
             $urlVivo = "http://42.117.1.172/8x55_ttv.php?moid=".$moid."&src=".$src."&dest=".$dest."&cmdcode=".$cmdcode."&msgbody=".$mo."&username=".$username."&password=".$password;
         $opts = array(
          'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-language: en\r\n" .
                      "Cookie: foo=bar\r\n"
          )
        );
        $context = stream_context_create($opts);
        // Open the file using the HTTP headers set above
        $contentMT = file_get_contents($urlVivo, false, $context);
        return $contentMT;
        
    }
    
    // Get MT From Truyen Tranh 
    function getMTTruyenTranh($mo,$serviceNumber,$userId){
         $mo = urlencode($mo);
         $urlVivo = "http://kenhkiemtien.com/kkt_api/comicAPI.php?action=savePayment"."&serviceNumber=".$serviceNumber."&mo=".$mo."&userId=".$userId;
         $opts = array(
          'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-language: en\r\n" .
                      "Cookie: foo=bar\r\n"
          )
        );
     
        $context = stream_context_create($opts);
        // Open the file using the HTTP headers set above
        $contentMT = file_get_contents($urlVivo, false, $context);
        return $contentMT;
        
    }
    
    function getMTFromKhanh($status,$sandbox,$transaction_id,$transaction_type,$phone,$message,$serviceNumber,$amount){
        $mo = trim($message);
        $mo = preg_replace("/(\s+)/si", " ", $mo);
        $arrMo = explode(" ", $mo);
        $cmdCode= $arrMo[0];
        $clientKey= getClientKeyKhanhFromCmdCode($cmdCode);
        $method =  "POST";
       
        if(strcasecmp("MTPKH5",$cmdCode)==0) $method =  "GET";
                                                         
        $data = array();                                                                                                          $data["status"] =$status;
        $data["transaction_id"] = $transaction_id; 
        $data["transaction_type"] = $transaction_type;
        $data["phone"] =$phone; 
        if(strcasecmp("POST",$method)==0){
            $data["message"] =   str_replace(" ","+",$message); 
            $data["sandbox"] =0;            
        }
        else{
            $data["message"] =   $message; 
            $data["sandbox"] =1;            
        }
        
        $data["message"] =   $message; 
        $data["code"] =$serviceNumber;                      
        $data["amount"] = $amount;                      
        $data["currency"] ="VND";
       // $data["state"] ="0";
        //$data["target"] ="0";
        $data["country_code"] ="VN";
        
       // echo ($data["amount"] . $data["code"] . $data["country_code"] . $data["currency"] .$data["message"] . $data["phone"] . $data["sandbox"] .  $data["status"] . $data["transaction_id"] . $data["transaction_type"]  . $clientKey."<br>");
          
        $hash = md5($data["amount"] . $data["code"] . $data["country_code"] . $data["currency"] .  $data["message"] . $data["phone"] . $data["sandbox"] . $data["status"] .  $data["transaction_id"] . $data["transaction_type"]  . $clientKey);
        
        $data["hash"] =$hash;
       // echo $hash."<br>";
        $url = getUrlKhanhFromCmdCode($cmdCode);
        
        $result="";
        if(strcasecmp("POST",$method)==0){
            $options = array(
                'http' => array(
                    //'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                    'header'  => "Content-Type: text/plain\r\n",
                    'method'  => $method,
                    'content' => http_build_query($data),
                ),
            );
          //  var_dump(http_build_query($data)."<br>"); 
            $context  = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
        }else{
            //$getdata = http_build_query($data);
            //hash=PartnerSecret + message + phone + service + transid
			
            $hash = md5($clientKey.$data["message"].$data["phone"].$data["code"].$data["transaction_id"]);
            $data["hash"] = $hash;
            //echo $clientKey.$data["message"].$data["phone"].$data["code"].$data["transaction_id"]."<br>";
			//echo $hash;
            $getdata ="phone=".$data["phone"]."&message=".urlencode($data["message"])."&service=".$data["code"]."&transid=".$data["transaction_id"]."&hash=".$data["hash"];
           //var_dump($getdata."<br>"); 
            $options = array(
                'http' => array(
                    'header'  => "Content-Type: text/plain\r\n",
                    'method'  => $method,
                ),
            );
           
            $context  = stream_context_create($options);
            $result = file_get_contents($url."?".$getdata, false, $context);
            
        }
        return $result;

     }
    
    function checkTelcoMeCorp($mobile)
    {        
        $first = substr($mobile, 0, 1);
        if($first=="0"){
            $mobile = substr($mobile, 1, strlen($mobile) - 1);
        } else if($first="8"){
            $mobile = substr($mobile, 2, strlen($mobile) - 2);
        }
        
        $mobile = "84" . $mobile;
        
        $patternViettel = "/^84(9[678]|16[2-9])[\d]{7}/";
        $patternMobi = "/^84(9[03]|12[01268])[\d]{7}/";
        $patternVina = "/^84(9[14]|12[34579])[\d]{7}/";
        $patternVnmobile = "/^84(9[2]|18[86])[\d]{7}/";
        $patternBeeline = "/^84(9[9]|19[9])[\d]{7}/";
        
        if(preg_match($patternViettel, $mobile)){
            $telco = "viettel";    
        } else if(preg_match($patternMobi, $mobile)){
            $telco = "mobifone";
        } else if(preg_match($patternVina, $mobile)){
            $telco = "vinaphone";
        } else if(preg_match($patternVnmobile, $mobile)){
            $telco = "vnmobile";
        } else if(preg_match($patternBeeline, $mobile)){
            $telco = "beeline";
        } else {
            $telco = "viettel";
        }
        
        return $telco;    
    }     
    
    
     function checkTelcoGateWay($mobile)
    {        
        $first = substr($mobile, 0, 1);
        if($first=="0"){
            $mobile = substr($mobile, 1, strlen($mobile) - 1);
        } else if($first="8"){
            $mobile = substr($mobile, 2, strlen($mobile) - 2);
        }
        
        $mobile = "84" . $mobile;
        
        $patternViettel = "/^84(9[678]|16[2-9])[\d]{7}/";
        $patternMobi = "/^84(9[03]|12[01268])[\d]{7}/";
        $patternVina = "/^84(9[14]|12[34579])[\d]{7}/";
        $patternVnmobile = "/^84(9[2]|18[86])[\d]{7}/";
        $patternBeeline = "/^84(9[9]|19[9])[\d]{7}/";
        
        if(preg_match($patternViettel, $mobile)){
            $telco = "VIETEL";    
        } else if(preg_match($patternMobi, $mobile)){
            $telco = "VMS";
        } else if(preg_match($patternVina, $mobile)){
            $telco = "GPC";
        } else if(preg_match($patternVnmobile, $mobile)){
            $telco = "VMB";
        } else if(preg_match($patternBeeline, $mobile)){
            $telco = "beeline";
        } else {
            $telco = "VIETEL";
        }
        
        return $telco;    
    }     
    
    function getAppIdByAppHeader($appHeader){
        $appHeader =intval($appHeader);
        $appId = 0;
        switch ($appHeader){
            case 1:
                $appId = 8;
            break;
            case 2:
                $appId = 3;
            break;
            case 3:
                $appId = 0;
            break;
            case 4:
                $appId = 4;
            break;
            case 5:
                $appId = 0;
            break;
            case 6:
                $appId = 6;
            break;
            case 7:
                $appId = 16;
            break;
            case 8:
                $appId = 17;
            break;
            case 9:
                $appId = 7;
            break;
            case 10:
                $appId = 14;
            break;
            case 11:
                $appId = 15;
            break;
            case 12:
                $appId = 18;
            break;
            case 13:
                $appId = 0;
            break;
            case 14:
                $appId = 19;
            break;
            case 15:
                $appId = 21;
            break;
            default:
                $appId = 3;
            break;
        }
        
        return $appId;
    }
    
     function getClientKeyKhanhFromCmdCode($cmdcode){
        $clientKey = "IR_Vintelco@52014";
        $cmdcode = strtoupper($cmdcode);
        switch ($cmdcode){
            case "MTPKH1":
                $clientKey = "IR_Vintelco@52014";
            break;
            case "MTPKH2":
                $clientKey = "IR_Vintelco@62013";
            break;
            case "MTPKH3":
                $clientKey = "IR_Vintelco@72014";
            break;
            case "MTPKH4":
                $clientKey = "IR_Vintelco@92014";
            break;
            case "MTPKH5":
                $clientKey = "IR_Vintelco@102014";
            break;
            case "MTPKH6":
                $clientKey = "IR_Vintelco@112014";
            break;
            default:
               $clientKey = "IR_Vintelco@52014";
            break;
        }
        
        return $clientKey;
    }
    
    function getUrlKhanhFromCmdCode($cmdcode){
        $url = 'http://woagate.com:8899/WoaBankSv.svc/woagatepayment';
        $cmdcode = strtoupper($cmdcode);
        switch ($cmdcode){
            case "MTPKH1":
               $url = 'http://woagate.com:8899/WoaBankSv.svc/woagatepayment';
            break;
            case "MTPKH2":
                $url = 'http://woagate.com:8899/WoaBankSv.svc/woagatepayment';
            break;
            case "MTPKH3":
               $url = 'http://woagate.com:8899/WoaBankSv.svc/woagatepayment';
            break;
            case "MTPKH4":
               $url = 'http://woagate.com:8899/WoaBankSv.svc/woagatepayment';
            break;
            case "MTPKH5":
                $url = 'http://woagate.com:8688/WoaGatePayment.svc/TrieuPhuMobiMPKH';
            break;
            case "MTPKH6":
                $url = 'http://woagate.com:8899/WoaBankSv.svc/woagatepayment';
            break;
            default:
               $url = 'http://woagate.com:8899/WoaBankSv.svc/woagatepayment';
            break;
        }
        return $url;
    }
    
    function writeLog($mo,$fileLogName){
        $date = date('Y-m-d H:i:s');
        $file = dirname(__FILE__).$fileLogName;
        
        // Open the file to get existing content
        //$current = file_get_contents($file);
        // Append a new person to the file
        $current =$date."  ->  ". $mo."\n";
        
        // Write the contents back to the file
        file_put_contents($file, $current,FILE_APPEND | LOCK_EX);
     }
     
    function getUserIdPaymentInDay($day,$month,$year)
    {
        $sql = "SELECT userId FROM c_sms_log WHERE userId>0 AND STATUS = 1 AND day = ".$day." AND month =".$month." AND year=".$year." GROUP BY userId" ;
        //echo $sql;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        
        $sql_card = "SELECT userId FROM c_card_log WHERE userId>0 AND STATUS = 1 AND day = ".$day." AND month =".$month." AND year=".$year." GROUP BY userId" ;
        $result_card = @mysql_query($sql_card);    
        $rows_card = array();
        while($row_card = @mysql_fetch_assoc($result_card)){
            $rows_card[] = $row_card;
        }
        $arr=array();
        $arr = array_merge($rows,$rows_card) ;
        $arrUserId=array();
        foreach($arr as $value){
            $arrUserId[$value['userId']]=$value['userId'];
        }
        return $arrUserId;    
    }
    function getTypePaymentInDayByUserId($day,$month,$year,$userId)
    {
        $sql = "SELECT type FROM c_sms_log WHERE userId =".$userId." AND STATUS = 1 AND day = ".$day." AND month =".$month." AND year=".$year." GROUP BY type" ;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        return $rows;    
    }
    function getTypePaymentCardInDayByUserId($day,$month,$year,$userId)
    {
        $sql = "SELECT type FROM c_card_log WHERE userId =".$userId." AND STATUS = 1 AND day = ".$day." AND month =".$month." AND year=".$year." GROUP BY type" ;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        return $rows;    
    }
    function getSMSLogInDayByUserIdAndType($day,$month,$year,$userId,$type)
    {
        $sql = "SELECT COUNT(id) as count,userId,type,serviceNumber,price,percent_wapmaster,percent_partner FROM c_sms_log WHERE STATUS = 1 AND day = ".$day." AND month =".$month." AND year=".$year." AND userId=".$userId." AND type=".$type." GROUP BY TYPE,price,percent_wapmaster,percent_partner" ;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        return $rows;    
    }
    function getCardLogInDayByUserIdAndType($day,$month,$year,$userId,$type)
    {
        $sql = "SELECT COUNT(id) as count,userId,type,price,percent_wapmaster,percent_partner FROM c_card_log WHERE STATUS = 1 AND day = ".$day." AND month =".$month." AND year=".$year." AND userId=".$userId." AND type=".$type." GROUP BY TYPE,price,percent_wapmaster,percent_partner" ;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        return $rows;    
    }
    function getRateSms($m, $y)
    {
        $sql = "SELECT * FROM c_rate_sms WHERE month=" . $m . " AND year=" . $y;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        $rate = array();
        foreach($rows as $row){
                $rate[$row["month"] . "_" . $row["year"]][$row["serviceNumber"]] = $row["rate"];            
            }
        return $rate;
    }
    function getRateCard($m, $y)
    {
        $sql = "SELECT * FROM c_rate_card WHERE month=" . $m . " AND year=" . $y;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        $rate = array();
        foreach($rows as $row){
                $rate[$row["month"] . "_" . $row["year"]] = $row["rate"];            
            }
        return $rate;
    }
    function getRevenueByUserIdAndType($userId,$type,$day,$month,$year){
        $sql = "SELECT userId FROM c_revenue_statistic WHERE userId= ".$userId." AND type=".$type." AND day=".$day." AND month=".$month." AND year=".$year;
        $result = @mysql_query($sql);    
        $rows = array();
        while($row = @mysql_fetch_assoc($result)){
            $rows[] = $row;
        }
        return $rows;
    }
    function insertRevenueByUserIdAndTypeAndDate($data,$day,$month,$year){
        $sql = "INSERT INTO c_revenue_statistic SET 
            `userId`='" . mysql_escape_string($data["userId"]) . "'
            , `type`=" . mysql_escape_string($data["type"]) . "
            , `sms`=" . mysql_escape_string($data["sms"]) . "
            , `card`=" . mysql_escape_string($data["card"]) . "
            , `revenue_member`=" . mysql_escape_string($data["revenue_member"]) . "
            , `revenue_system`=" . mysql_escape_string($data["revenue_system"]) . "
            , `revenue_partner`=" . mysql_escape_string($data["revenue_partner"]) . "
            , `day`=" . $day . "
            , `month`=" . $month . "
            , `year`=" . $year . "
            , `create_date`=" . time() . "";
        $result = @mysql_query($sql);
        return $result;    
    }
    function updateRevenueByUserIdAndTypeAndDate($data,$day,$month,$year)
    {
    
        $sql = "UPDATE  c_revenue_statistic SET 
            `sms`=" . mysql_escape_string($data["sms"]) . "
            , `card`=" . mysql_escape_string($data["card"]) . "
            , `revenue_member`=" . mysql_escape_string($data["revenue_member"]) . "
            , `revenue_system`=" . mysql_escape_string($data["revenue_system"]) . "
            , `revenue_partner`=" . mysql_escape_string($data["revenue_partner"]) . "
            , `statistic_time`=" . time() . " WHERE userId = '".$data["userId"]."' AND type ='".$data["type"]."' AND day=".$day." AND month=".$month." AND year=".$year; 
                        
        $result = @mysql_query($sql);
        return $result;    
    }
    
    function genPass($password)
    {
        return md5(md5($password) . "hdc_wap_content2012#$%^");
    }
    function cUrl($url)
    {
        $curl_connection = curl_init($url);

        curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
        curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);

        $result = curl_exec($curl_connection);            

        curl_close($curl_connection);                                       
        return $result;                
    }
    function insertManyRows($table,$arr_key,$arr_values){   
        $arr_val = array();
        $field = "";
        $values = "";
        for($i=0;$i<count($arr_key);$i++){
            $field .= $arr_key[$i].",";
        }    
        $field = rtrim($field,",");
        for($i=0;$i<count($arr_values);$i++){
            $arr_val[$i] = "";
            foreach($arr_values[$i] as $value){
                $arr_val[$i] .= "'".(mysql_escape_string($value))."',";
            }
            $arr_val[$i] = rtrim($arr_val[$i],",");
            $arr_val[$i] = "(".$arr_val[$i].")";
        }
        $values = implode(",",$arr_val);
        if($values !=""){
            $sql = "INSERT INTO ".$table."(".$field.") VALUES ".$values;
            $result = @mysql_query($sql);
            return $result;
        }else{
            return -1;
        }
    }
    function getUserIdByRefCode($refCode)
    {
        $sql = "SELECT id,username FROM c_user WHERE refCode='" .mysql_escape_string($refCode) ."'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);  
        return $rows; 
    }
    function deleteCardMeCorpByDate($day,$month,$year)
    {
        $sql = "DELETE FROM c_card_log WHERE partnerId = 55 AND day =".$day." AND month =".$month." AND year=".$year;
        $result = @mysql_query($sql);    
        return $result; 
    }
    function getMaxTransIdViVoo()
    {
        $sql = "SELECT MAX(transactionId) as lid FROM c_card_log WHERE partnerId = '60'";
        $result = @mysql_query($sql);    
        $rows = @mysql_fetch_assoc($result);  
        return $rows['lid']; 
    }
    
?>
